package android.mcsmtms.fragment;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.google.gson.Gson;

import android.app.Activity;
import android.content.Context;
import android.mcsmtms.R;
import android.mcsmtms.activity.SendReportActivity;
import android.mcsmtms.constant.GlobalConstants;
import android.mcsmtms.domain.SituationReport;
import android.mcsmtms.domain.User;
import android.mcsmtms.rest.RestClient;
import android.mcsmtms.util.Utilities;
import android.os.AsyncTask;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class NotificationsCustomAdapter extends ArrayAdapter<SituationReport> {
	private Activity context;
	private int layoutResourceId;
	private List<SituationReport> notificationList = new ArrayList<SituationReport>();
	public static final String APPROVE_REPORT_REST_SERVICE_URL = GlobalConstants.RestUrls.APPROVE_REPORT_REST_SERVICE_URL;
	public static final String REJECT_REPORT_REST_SERVICE_URL = GlobalConstants.RestUrls.REJECT_REPORT_REST_SERVICE_URL;
	
	private static final String SITUATION_ID_PARAM = "situationId";
	private static final String APPROVE_OPERATION = "APPROVE";
	private static final String REJECT_OPERATION = "REJECT";
	private static final String OPERATION_PARAM = "operation";
	private RefreshNotificationListCallback refreshNotificationsCallback;

	public NotificationsCustomAdapter(Activity context, int layoutResourceId,
			List<SituationReport> data, RefreshNotificationListCallback refreshNotificationListCallback) {
		super(context, layoutResourceId, data);
		this.layoutResourceId = layoutResourceId;
		this.context = context;
		this.notificationList = data;
		this.refreshNotificationsCallback = refreshNotificationListCallback;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		View row = convertView;
		NotificationHolder holder = null;

		if (row == null) {
			LayoutInflater inflater = ((Activity) context).getLayoutInflater();
			row = inflater.inflate(layoutResourceId, parent, false);
			holder = new NotificationHolder();
			holder.situationReportDetails = (TextView) row.findViewById(R.id.textView1);
			holder.btnApprove = (Button) row.findViewById(R.id.button1);
			holder.btnReject = (Button) row.findViewById(R.id.button2);
			row.setTag(holder);
		} else {
			holder = (NotificationHolder) row.getTag();
		}
		SituationReport situationReport = notificationList.get(position);
		holder.situationReportDetails.setText(Utilities.generateSituationDetails(situationReport));
		//holder.situationReportDetails.setTextSize(8);

		holder.btnApprove.setOnClickListener(new ApproveOnClickListener(position));
		holder.btnReject.setOnClickListener(new RejectOnClickListener(position));
		return row;

	}
	
	class ApproveOnClickListener implements OnClickListener {
		private int position;
		
		public ApproveOnClickListener(int position) {
			this.position = position;
		}
		
		@Override
		public void onClick(View v) {
			String situationId = notificationList.get(position).getId().toString();
			ApproveRejectTask approveTask = new ApproveRejectTask();
			Map<String, Object> approveReportParams = new HashMap<String, Object>();
			approveReportParams.put(OPERATION_PARAM, APPROVE_OPERATION);
			approveReportParams.put(SITUATION_ID_PARAM, situationId);
			
			approveTask.execute(approveReportParams);
			
			Log.i("Approve Button Clicked", "**********");
			Toast.makeText(context, "Approve button Clicked On Row " + situationId,
					Toast.LENGTH_SHORT).show();
		}
		
	}
	
	class RejectOnClickListener implements OnClickListener {
		private int position;
		
		public RejectOnClickListener(int position) {
			this.position = position;
		}
		
		@Override
		public void onClick(View v) {
			String situationId = notificationList.get(position).getId().toString();
			ApproveRejectTask rejectTask = new ApproveRejectTask();
			Map<String, Object> rejectReportParams = new HashMap<String, Object>();
			rejectReportParams.put(OPERATION_PARAM, REJECT_OPERATION);
			rejectReportParams.put(SITUATION_ID_PARAM, situationId);
			
			rejectTask.execute(rejectReportParams);
			
			Log.i("Approve Button Clicked", "**********");
			Toast.makeText(context, "Approve button Clicked On Row " + situationId,
					Toast.LENGTH_SHORT).show();
		}
		
	}

	static class NotificationHolder {
		TextView situationReportDetails;
		Button btnApprove;
		Button btnReject;
	}
	
	public class ApproveRejectTask extends AsyncTask<Map<String, Object>, Void, Boolean> {
		@Override
		protected Boolean doInBackground(Map<String, Object>... params) {
			String situationId;
			String operation;
			if(null != params) {
				situationId = params[0].get("situationId").toString(); 
				operation = params[0].get("operation").toString();
				if(situationId == null || situationId.isEmpty())
					return false;
				if(operation == null || operation.isEmpty())
					return false;
			} else return false;
			
			try {
				// Simulate network access.
				//Thread.sleep(2000);
				String url = "";
				if(APPROVE_OPERATION.equals(operation)) {
					url = APPROVE_REPORT_REST_SERVICE_URL;
				} else if(REJECT_OPERATION.equals(operation)) {
					url = REJECT_REPORT_REST_SERVICE_URL;
				}
				User loggedUser = Utilities.getLoggedUser(context);
				RestClient client = new RestClient(url, loggedUser.getUserName(), loggedUser.getPassword());

				//situationId = Utilities.encodeBase64UrlSafe(situationId);
				
			    client.addParam("situationId", situationId);
			    
			    client.execute(RestClient.RequestMethod.POST);
				
				String response = client.getResponse();
				Log.i("Approve/Reject Report", response);
				
			    if(response != null) {
			    	//Toast.makeText(getParent(), "GPS Enabled!", Toast.LENGTH_SHORT).show();
			    	return true;
			    } else {
			    	return false;
			    }
			} catch (Exception e) {
				Log.e("Approve/Reject Report", e.getLocalizedMessage());
				return false;
			}
		}

		@Override
		protected void onPostExecute(final Boolean success) {
			//showProgress(false);

			if (success) {
				Toast.makeText(context, "Report processed!", Toast.LENGTH_SHORT).show();
				Log.i("ApproveRejectReport", "Report processed!");
				refreshNotificationsCallback.refreshNotificationsList();
			} else {
				Toast.makeText(context, "Report not processed!", Toast.LENGTH_SHORT).show();
				Log.i("ApproveRejectReport", "Report not processed!");
			}
		}

		@Override
		protected void onCancelled() {
			//showProgress(false);
		}
	}
}